import React from 'react';
import {connect} from 'dva';
import {Card, Form, Input, Icon, Button, Upload, Modal, Row, Col, Select, Cascader, Affix} from 'antd';
import ContentWrapper from '../layouts/ContentWrapper';
import {beforeUpload, arrayToTree} from "../../utils/utils";
import {qiniuConfig, tagData} from '../../config/config';
import BraftEditor from 'braft-editor';
import KEditor from "../../components/KEditor";

const FormItem = Form.Item;
const Option = Select.Option;
const {TextArea} = Input;

@connect(state => ({
  loading: state.loading,
  postCat: state.postCat,
  post: state.post,
}))
@Form.create()
export default class PostCU extends React.PureComponent {

  constructor(props) {
    super(props);

    const {match: {params}} = this.props;
    this.state = {
      opType: params.id ? 'edit' : 'new',
      fileList: [],
      previewVisiable: false,
      previewImage: '',
      editorState: null,
    };
  }

  componentDidMount() {
    const {dispatch, match: {params}} = this.props;

    if (params.id) {
      dispatch({
        type: 'post/get',
        payload: params.id,
      });
    }

    dispatch({
      type: 'postCat/getAll',
    });
  }

  UNSAFE_componentWillReceiveProps(nextProps) {
    const currentMatchedId = this.props.match.params.id;
    const nextMatchedId = nextProps.match.params.id;
    if (nextMatchedId && currentMatchedId !== nextMatchedId) {
      this.props.dispatch({
        type: 'post/get',
        payload: nextMatchedId
      });
    }

    // TODO optimize (add compare between old and new props)
    if (this.state.fileList.length === 0 && nextProps.post.item && nextProps.post.item.img) {
      const fileList = [{
        uid: -1,
        name: 'xxx.png',
        status: 'done',
        url: nextProps.post.item.img,
      }];
      this.setState({fileList});
    }

    if (!this.props.post.item.content && nextProps.post.item.content) {
      this.setState({
        editorState: BraftEditor.createEditorState(nextProps.post.item.content)
      })
    }
  }

  componentWillUnmount() {
    this.props.dispatch({
      type: 'post/cleanItem',
    });
  }

  handleUploadChange = ({file, fileList}) => {
    const {status, response = {}} = file;
    if (status === 'done') {
      this.props.form.setFieldsValue({
        img: qiniuConfig.baseExternalLink + (response.hash || ''),
      });
    } else if (status === 'removed') {
      this.props.form.setFieldsValue({
        img: '',
      });
    }
    this.setState({fileList});
  };

  handlePreview = file => {
    this.setState({
      previewImage: file.url || file.thumbUrl,
      previewVisible: true,
    });
  };

  handleClosePreviewModal = () => this.setState({previewVisible: false});

  handleEditorChange = editorState => {
    this.setState({
      editorState,
    });
  };

  handleSubmit = (e) => {
    e.preventDefault();
    const {dispatch, postCat: {list}, form: {validateFieldsAndScroll}} = this.props;
    const {opType, editorState} = this.state;

    validateFieldsAndScroll((errors, values) => {
      if (errors) {
        return;
      }

      const cids = values.cids;
      const cid1 = Number(cids[0]);
      const cid2 = Number(cids[1]);
      const cat1 = list.find(item => item.id === cid1);
      const cat2 = list.find(item => item.id === cid2);

      const data = {
        ...values,
        cid1,
        cid2,
        cname1: cat1.name,
        cname2: cat2 && cat2.name,
        tags: values.tags.join(','),
        negotiable: values.negotiable ? 1 : 0,
        content: editorState.toHTML().replace(/\<img/gi, '<img style="max-width:100%;height:auto" '),
      };

      // TODO for editor
      // console.log(data);

      if (opType === 'new') {
        dispatch({
          type: `post/create`,
          payload: data,
        });
      } else {
        const {post: {item}} = this.props;
        dispatch({
          type: `post/update`,
          payload: {
            id: item.id,
            data
          },
        });
      }
    });
  };

  render() {
    const {history, loading, postCat: {list}, form: {getFieldDecorator}, post: {item}} = this.props;
    const {opType, previewVisible, previewImage, fileList, editorState} = this.state;
    const itemLoading = loading.effects['post/get'];
    const formLoading = opType === 'new' ? loading.effects['post/create'] : loading.effects['post/update'];

    const formItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 4},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 20},
      },
    };

    const editorFormItemLayout = {
      labelCol: {
        xs: {span: 24},
        sm: {span: 2},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 22},
      },
    };

    const tailFormItemLayout = {
      wrapperCol: {
        xs: {span: 24, offset: 0},
        sm: {span: 22, offset: 2},
      },
    };

    const catTree = arrayToTree(list.map(item => ({
      id: item.id,
      pid: item.pid,
      label: item.name,
      value: item.id.toString(),
    })), 'id', 'pid');

    const tagOptions = tagData.map(item => <Option key={item}>{item}</Option>);

    return (
      <ContentWrapper loading={itemLoading}>
        <Card
          title={opType === 'new' ? '新增内容' : '编辑内容'}
          bordered={false}
        >
          <Form>
            <Row gutter={16}>
              <Col span={12}>
                {getFieldDecorator('img', {
                  initialValue: item.img,
                })(
                  <Input type="hidden"/>
                )}
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="名称"
                >
                  {getFieldDecorator('name', {
                    initialValue: item.name,
                    rules: [{
                      required: true,
                      message: '请输入名称！',
                    }],
                  })(
                    <Input/>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="分类"
                >
                  {getFieldDecorator('cids', {
                    initialValue: [item.cid1 && item.cid1.toString(), item.cid2 && item.cid2.toString()],
                    rules: [{
                      required: true,
                      message: '请选择分类！',
                    }],
                  })(
                    <Cascader
                      options={catTree}
                      placeholder="Please select"
                      expandTrigger="hover"
                      changeOnSelect
                    />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  hasFeedback
                  label="标签"
                >
                  {getFieldDecorator('tags', {
                    initialValue: item.tags ? item.tags.split(',') : [],
                  })(
                    <Select
                      mode="tags"
                      style={{width: '100%'}}
                    >
                      {tagOptions}
                    </Select>
                  )}
                </FormItem>
              </Col>
              <Col span={12}>
                <Upload
                  name="file"
                  listType="picture-card"
                  className="avatar-uploader"
                  action={`${qiniuConfig.server}`}
                  data={{token: qiniuConfig.token}}
                  fileList={fileList}
                  beforeUpload={beforeUpload}
                  onChange={this.handleUploadChange}
                  onPreview={this.handlePreview}
                >
                  {fileList.length >= 1
                    ? null
                    : <div>
                      <Icon type="plus"/>
                      <div className="ant-upload-text">Upload</div>
                    </div>
                  }
                </Upload>
              </Col>
              <Col span={24}>
                <FormItem
                  {...editorFormItemLayout}
                  hasFeedback
                  label="摘要"
                >
                  {getFieldDecorator('excerpt', {
                    initialValue: item.excerpt,
                  })(
                    <TextArea rows={4}/>
                  )}
                </FormItem>
                <FormItem
                  {...editorFormItemLayout}
                  hasFeedback
                  label="内容"
                >
                  <KEditor
                    value={editorState}
                    onChange={this.handleEditorChange}
                  />
                </FormItem>
                <FormItem {...tailFormItemLayout}>
                  <Affix offsetBottom={10}>
                    <Button onClick={() => history.goBack()}>取消</Button>
                    <Button style={{marginLeft: 8}} type="primary" onClick={this.handleSubmit} loading={formLoading}>提交</Button>
                  </Affix>
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Card>
        <Modal
          visible={previewVisible}
          footer={null}
          onCancel={this.handleClosePreviewModal}
        >
          <img alt="example" style={{width: '100%'}} src={previewImage}/>
        </Modal>
      </ContentWrapper>
    );
  }
}
